package com.question_barrier.service.impl;

import com.question_barrier.entity.User;
import com.question_barrier.repository.UserRepository;
import com.question_barrier.result.StateCode;
import com.question_barrier.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public List<User> getAllUser() {
        return userRepository.findAll();
    }

    @Override
    public int addUser(User user) {
        if (userRepository.existsById(user.getId())) {
            System.out.println("user is existed");
            return StateCode.ADDFAIL;
        }
        User saveUser = userRepository.save(user);
        if (saveUser != null && saveUser.getId() == user.getId()) {
            System.out.println("save success");
            return StateCode.ADDSUCCESS;
        } else {
            System.out.println("save failure");
            return StateCode.ADDFAIL;
        }
    }

    @Override
    public int deleteUser(long id) {
        /**
         * 检测到原本没有这个数据直接报错
         */
        if (userRepository.existsById(id)) {
            userRepository.deleteById(id);
            System.out.println("删除成功");
            return StateCode.DELETESUCCESS;
        }
        System.out.println("删除失败");
        return StateCode.DELETEFAIL;
    }

    @Override
    public int updateUser(User user) {
        if (userRepository.existsById(user.getId())) {
            userRepository.save(user);
            System.out.println("更新成功");
            return StateCode.UPDATESUCCESS;
        }
        System.out.println("更新失败");
        return StateCode.UPDATEFAIL;
    }

    @Override
    public User queryUser(long id) {
        User user = null;
        if (userRepository.existsById(id)) {
            user = userRepository.findById(id).get();
            System.out.println(user.toString());
        }
        return user;
    }


    @Override
    public User findByOpenId(String openId) {
        return userRepository.findByOpenId(openId);
    }

    @Override
    public List<User> getTop10() {
        PageRequest pageRequest = PageRequest.of(0, 10, new Sort(Sort.Direction.DESC, "integral"));
        return userRepository.findAll(pageRequest).getContent();
    }

    @Override
    public boolean existsByOpenId(String openId) {
        return userRepository.existsByOpenId(openId);
    }

}